<template>
  <el-drawer v-model="dialogVisible" :title="dialogStatus==='create'?'新增': (dialogStatus === 'view' ? '查看' : '编辑')"
    width="600px" @close="reset">
    <el-form ref="formRef" :model="tableItem" :rules="rules" label-width="180" label-position="top"
      :disabled="!isDisabled">
      <el-form-item label="所属商户" prop="tenantId">
        <el-select v-model="tableItem.tenantId" placeholder="请选择商户" clearable filterable>
          <el-option v-for="item in merchantList" :label="item.tenantName" :value="item.id" :key="item.id" />
        </el-select>
        <div style="font-size: 12px; color: #999; margin-top: 4px;">
          当前可选商户数量: {{ merchantList.length }}
        </div>
        <div v-if="merchantList.length === 0" style="font-size: 12px; color: #f56c6c; margin-top: 4px;">
          暂无可选商户，请联系管理员添加商户
        </div>
      </el-form-item>

      <el-form-item label="企业名称" prop="name">
        <el-input v-model="tableItem.name" placeholder="请输入企业名称" />
      </el-form-item>

      <el-form-item label="企业简称" prop="shortName">
        <el-input v-model="tableItem.shortName" placeholder="请输入企业简称" />
      </el-form-item>

      <el-form-item label="结算周期" prop="billingCycle">
        <el-select v-model="tableItem.billingCycle" placeholder="请选择结算周期" style="width: 60%" filterable clearable>
          <el-option v-for="item in billingCycleOption" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="tableItem.contactPerson" placeholder="请输入联系人" />
      </el-form-item>

      <el-form-item label="联系电话" prop="customerPhone">
        <el-input v-model="tableItem.customerPhone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="公司地址" prop="companyAddress">
        <el-input v-model="tableItem.companyAddress" placeholder="请输入公司地址" />
      </el-form-item>

      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="tableItem.email" placeholder="请输入电子邮箱" />
      </el-form-item>

      <el-form-item label="经营场景" prop="businessScenario">
        <el-input v-model="tableItem.businessScenario" placeholder="请输入经营场景" />
      </el-form-item>

      <el-form-item label="所属行业" prop="industry">
        <el-select v-model="tableItem.industry" placeholder="请选择所属行业">
          <el-option v-for="item in industryList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="租房面积(单位：平方米)" prop="rentalArea">
        <el-input v-model.number="tableItem.rentalArea" type="number" min="0" placeholder="请输入租房面积" />
      </el-form-item>

      <el-form-item label="所在地点位置" prop="location">
        <div class="location-selector">
          <el-input v-model="tableItem.location" placeholder="请选择地点位置" readonly style="margin-bottom: 8px;" />
          <el-button type="primary" @click="openLocationDialog" style="width: 100%;">
            <el-icon>
              <House />
            </el-icon>
            选择地点位置
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="营业执照图片" prop="businessLicensePic">
        <el-upload class="upload-demo" :http-request="handleBusinessLicenseUpload" :before-upload="beforeUpload"
          :limit="1" list-type="picture"
          :file-list="tableItem.businessLicensePic ? [{ name: '营业执照', url: tableItem.businessLicensePic }] : []"
          :on-remove="() => { tableItem.businessLicensePic = ''; formRef?.clearValidate('businessLicensePic') }">
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">请上传营业执照图片</div>
          </template>
        </el-upload>
        <div v-if="dialogStatus === 'view' && tableItem.businessLicensePic" class="image-preview">
          <img :src="tableItem.businessLicensePic" alt="营业执照" style="max-width: 100%; max-height: 200px;" />
        </div>
      </el-form-item>

      <el-form-item label="法人正面图片" prop="legalPersonFrontPic">
        <el-upload class="upload-demo" :http-request="handleLegalPersonFrontUpload" :before-upload="beforeUpload"
          :limit="1" list-type="picture"
          :file-list="tableItem.legalPersonFrontPic ? [{ name: '法人正面', url: tableItem.legalPersonFrontPic }] : []"
          :on-remove="() => { tableItem.legalPersonFrontPic = ''; formRef?.clearValidate('legalPersonFrontPic') }">
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">请上传法人正面图片</div>
          </template>
        </el-upload>
        <div v-if="dialogStatus === 'view' && tableItem.legalPersonFrontPic" class="image-preview">
          <img :src="tableItem.legalPersonFrontPic" alt="法人正面" style="max-width: 100%; max-height: 200px;" />
        </div>
      </el-form-item>

      <el-form-item label="法人背面图片" prop="legalPersonBackPic">
        <el-upload class="upload-demo" :http-request="handleLegalPersonBackUpload" :before-upload="beforeUpload"
          :limit="1" list-type="picture"
          :file-list="tableItem.legalPersonBackPic ? [{ name: '法人背面', url: tableItem.legalPersonBackPic }] : []"
          :on-remove="() => { tableItem.legalPersonBackPic = ''; formRef?.clearValidate('legalPersonBackPic') }">
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">请上传法人背面图片</div>
          </template>
        </el-upload>
        <div v-if="dialogStatus === 'view' && tableItem.legalPersonBackPic" class="image-preview">
          <img :src="tableItem.legalPersonBackPic" alt="法人背面" style="max-width: 100%; max-height: 200px;" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer v-if="isDisabled">
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确 定</el-button>
      </span>
    </template>

    <!-- 地点位置选择对话框 -->
    <LocationSelectDialog ref="locationDialogRef" @confirm="handleLocationConfirm" />
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { House } from '@element-plus/icons-vue'
import { addEnterprise, editEnterprise, getMerchant, getMerchantByName, uploadFile } from '@/api/settle'
import { validate } from '@/utils/validate'
import { getDist } from '@/api/collect'
import LocationSelectDialog from './LocationSelectDialog.vue'

const billingCycleOption = ref<any>([
  { name: '按月结算', value: 0 },
  { name: '按季度结算', value: 1 },
  { name: '按半年结算', value: 2 },
  { name: '按年结算', value: 3 },
])
const industryList = ref<any>([])

// 商户列表
const merchantList = ref<any[]>([])
// 获取商户列表
const getMerchantList = (name?: string) => {
  // 使用新的按名称查询接口
  getMerchantByName(name).then((res: any) => {
    if (res.success && res.data) {
      merchantList.value = Array.isArray(res.data) ? res.data : []
    } else {
      console.warn('未获得到商户列表:', res)
      merchantList.value = []
    }
  }).catch((err: any) => {
    console.error('获取商户列表失败', err)    
  })
}

// 页面加载时获取所属行业列表和商户列表
onMounted(() => {
  getDistData()
  getMerchantList()
})

const isDisabled = ref(true)

const tableItem = reactive({
  id: undefined as number | undefined,
  tenantId: undefined as number | undefined,
  name: '',
  shortName: '',
  billingCycle: undefined as number | undefined,
  contactPerson: '',
  customerPhone: '',
  email: '',
  industry: '',
  businessScenario: '',
  rentalArea: undefined as number | undefined,
  companyAddress: '',
  location: '',
  locationId: undefined as number | undefined,
  businessLicensePic: '',
  legalPersonFrontPic: '',
  legalPersonBackPic: ''
})

const rules = reactive({
  tenantId: [{ required: true, message: '请选择所属商户', trigger: 'change' }],
  name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  shortName: [{ required: true, message: '请输入企业简称', trigger: 'blur' }],
  billingCycle: [{ required: true, message: '请选择结算周期', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  customerPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  email: [
    { required: false, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  //industry: [{ required: true, message: '请输入所属行业', trigger: 'blur' }],
  //businessScenario: [{ required: true, message: '请选择经营场景', trigger: 'change' }],
  //rentalArea: [
  //  { required: false, message: '请输入租房面积', trigger: 'blur' },
  //  { type: 'number', message: '租房面积必须为数字', trigger: 'blur' }
  //],
  companyAddress: [{ required: true, message: '请输入公司地址', trigger: 'blur' }],
  location: [{ required: false, message: '请输入所在地点位置', trigger: 'blur' }],
/*   businessLicensePic: [{ 
    required: false, 
    message: '请上传营业执照图片', 
    trigger: 'change',
    validator: (rule: any, value: any, callback: any) => {
      if (!value || value === '') {
        callback(new Error('请上传营业执照图片'))
      } else {
        callback()
      }
    }
  }],
  legalPersonFrontPic: [{ 
    required: false, 
    message: '请上传法人正面图片', 
    trigger: 'change',
    validator: (rule: any, value: any, callback: any) => {
      if (!value || value === '') {
        callback(new Error('请上传法人正面图片'))
      } else {
        callback()
      }
    }
  }],
  legalPersonBackPic: [{ 
    required: false, 
    message: '请上传法人背面图片', 
    trigger: 'change',
    validator: (rule: any, value: any, callback: any) => {
      if (!value || value === '') {
        callback(new Error('请上传法人背面图片'))
      } else {
        callback()
      }
    }
  }] */
})

const getDistData = () => {
  getDist('DC00012')
  .then((res: any)=>{
    industryList.value = res.data
  })
}

const dialogVisible = ref(false)
const dialogStatus = ref('create')

// 文件上传前的验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传函数
const customUpload = async (options: any, field: string) => {
  console.log('=== 开始自定义上传 ===')
  console.log('上传选项:', options)
  console.log('字段名:', field)
  
  const formData = new FormData()
  formData.append('files', options.file)
  
  console.log('FormData 内容:', formData.get('files'))
  
  try {
    const response = await uploadFile(formData)
    console.log('上传响应:', response)
    console.log('响应数据类型:', typeof response.data)
    console.log('响应数据内容:', response.data)
    
    let imageUrl = ''
    
    if (response.code === 200 && response.data) {
      // 处理数组格式的响应
      if (Array.isArray(response.data) && response.data.length > 0) {
        // 如果 data 是数组，取第一个元素
        const firstItem = response.data[0]
        if (typeof firstItem === 'string') {
          imageUrl = firstItem
        } else if (firstItem && firstItem.url) {
          imageUrl = firstItem.url
        }
        console.log('从数组中提取的URL:', imageUrl)
      } else if (typeof response.data === 'string') {
        // 如果 data 直接是字符串
        imageUrl = response.data
        console.log('直接使用字符串URL:', imageUrl)
      } else if (response.data.url) {
        // 如果 data 是对象且有 url 属性
        imageUrl = response.data.url
        console.log('从对象中提取的URL:', imageUrl)
      }
    }
    
    console.log('最终提取的图片URL:', imageUrl)
    
    if (imageUrl && imageUrl.trim() !== '') {
      (tableItem as any)[field] = imageUrl.trim()
      console.log(`${field} 设置为:`, imageUrl.trim())
      console.log('当前 tableItem 状态:', JSON.stringify(tableItem, null, 2))
      
      // 清除验证错误
      if (formRef.value) {
        formRef.value.clearValidate(field)
      }
      
      ElMessage.success('上传成功')
      options.onSuccess(response)
    } else {
      console.error('无法从响应中提取图片URL:', response)
      ElMessage.error('上传失败：无法获取图片地址')
      options.onError(new Error('上传失败'))
    }
  } catch (error) {
    console.error('上传出错:', error)
    ElMessage.error('上传失败：' + (error as any).message)
    options.onError(error)
  }
  
  console.log('=== 自定义上传结束 ===')
}

// 营业执照上传处理
const handleBusinessLicenseUpload = (options: any) => {
  return customUpload(options, 'businessLicensePic')
}

// 法人正面照片上传处理
const handleLegalPersonFrontUpload = (options: any) => {
  return customUpload(options, 'legalPersonFrontPic')
}

// 法人背面照片上传处理
const handleLegalPersonBackUpload = (options: any) => {
  return customUpload(options, 'legalPersonBackPic')
}

const reset = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  Object.assign(tableItem, {
    id: undefined,
    tenantId: undefined,
    name: '',
    shortName: '',
    billingCycle: '',
    contactPerson: '',
    customerPhone: '',
    email: '',
    industry: '',
    businessScenario: '',
    rentalArea: undefined,
    companyAddress: '',
    location: '',
    locationId: undefined,
    businessLicensePic: '',
    legalPersonFrontPic: '',
    legalPersonBackPic: ''
  })
}

const formRef = ref<any>(null)

const emit = defineEmits(['listChange'])

const createData = async () => {
  console.log('开始创建企业，当前表单数据:', tableItem)
  
  const valid = await validate(formRef)
  if (valid) {
    // 确保图片字段是字符串而不是数组
    const businessLicensePic = Array.isArray(tableItem.businessLicensePic) ? tableItem.businessLicensePic[0] || '' : tableItem.businessLicensePic
    const legalPersonFrontPic = Array.isArray(tableItem.legalPersonFrontPic) ? tableItem.legalPersonFrontPic[0] || '' : tableItem.legalPersonFrontPic
    const legalPersonBackPic = Array.isArray(tableItem.legalPersonBackPic) ? tableItem.legalPersonBackPic[0] || '' : tableItem.legalPersonBackPic
    
    const requestData = {
      name: tableItem.name,
      shortName: tableItem.shortName,
      billingCycle: tableItem.billingCycle,
      contactPerson: tableItem.contactPerson,
      customerPhone: tableItem.customerPhone,
      email: tableItem.email,
      industry: tableItem.industry,
      businessScenario: tableItem.businessScenario,
      rentalArea: tableItem.rentalArea,
      companyAddress: tableItem.companyAddress,
      locationId: tableItem.locationId,
      businessLicensePic: businessLicensePic,
      legalPersonFrontPic: legalPersonFrontPic,
      legalPersonBackPic: legalPersonBackPic,
      tenantId: tableItem.tenantId
    }
    
    addEnterprise(requestData)
    .then(() => {
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('创建企业成功！')
    })
    .catch((err) => {
      ElMessage.error(err.msg || '创建失败')
    })
  }
}

const updateData = async () => {
  const valid = await validate(formRef)
  if (valid) {
    // 确保 tenantId 不为 undefined 或空值且有 id
    if (tableItem.tenantId === undefined || tableItem.tenantId === null) {
      ElMessage.error('请选择所属商户')
      return
    }
    
    if (!tableItem.id) {
      ElMessage.error('缺少企业ID')
      return
    }
    
    // 确保图片字段是字符串而不是数组
    const requestData = {
      id: tableItem.id,
      name: tableItem.name,
      shortName: tableItem.shortName,
      billingCycle: tableItem.billingCycle,
      contactPerson: tableItem.contactPerson,
      customerPhone: tableItem.customerPhone,
      email: tableItem.email,
      industry: tableItem.industry,
      businessScenario: tableItem.businessScenario,
      rentalArea: tableItem.rentalArea,
      companyAddress: tableItem.companyAddress,
      locationId: tableItem.locationId,
      businessLicensePic: Array.isArray(tableItem.businessLicensePic) ? tableItem.businessLicensePic[0] || '' : tableItem.businessLicensePic,
      legalPersonFrontPic: Array.isArray(tableItem.legalPersonFrontPic) ? tableItem.legalPersonFrontPic[0] || '' : tableItem.legalPersonFrontPic,
      legalPersonBackPic: Array.isArray(tableItem.legalPersonBackPic) ? tableItem.legalPersonBackPic[0] || '' : tableItem.legalPersonBackPic,
      tenantId: tableItem.tenantId
    }

    editEnterprise(requestData)
    .then(() => {
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('更新企业成功！')
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
  }
}

// 地点位置选择相关
const locationDialogRef = ref()

const openLocationDialog = () => {
  console.log('打开地点位置选择对话框')
  
  // 检查是否选择了商户（需要tenantId）
  if (!tableItem.tenantId) {
    ElMessage.warning('请先选择所属商户')
    return
  }
  
  if (locationDialogRef.value) {
    // 使用选择模式打开地点位置选择对话框
    locationDialogRef.value.openDialog(tableItem.tenantId)
  } else {
    ElMessage.error('地点位置选择组件未正确加载')
  }
}

const handleLocationConfirm = (selectedLocation: any) => {
  if (selectedLocation) {
    // 构建地点位置路径
    const getLocationPath = (location: any): string => {
      // 如果已经有完整路径，直接使用
      if (location.path) {
        return location.path
      }
      
      // 如果有层级信息，构建完整路径
      if (location.parentPath) {
        return `${location.parentPath} > ${location.name}`
      }
      
      // 否则使用名称
      return location.name || '未知位置'
    }
    
    const locationPath = getLocationPath(selectedLocation)
    
    // 存储地点位置ID和显示名称
    tableItem.locationId = selectedLocation.id
    tableItem.location = locationPath
    
    // 清除验证错误
    if (formRef.value) {
      formRef.value.clearValidate('location')
    }    
  }
}

defineExpose({ dialogVisible, tableItem, isDisabled, dialogStatus, reset })
</script>

<style scoped>
.location-selector {
  width: 100%;
}

.image-preview {
  margin-top: 8px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>